package com.videoaggre.zcl.db

import androidx.room.*
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.TypeReference
import com.videoaggre.zcl.App
import com.videoaggre.zcl.bean.QimanComicChapter
import com.videoaggre.zcl.bean.QimanComicHomeNormal
import com.videoaggre.zcl.bean.QimanComicPre
import com.videoaggre.zcl.utils.MoshiUtils
import java.lang.reflect.ParameterizedType
import java.util.*
import kotlin.collections.ArrayList

private val DB: AppDatabase by lazy {
    Room.databaseBuilder(
        App.app,
        AppDatabase::class.java, "videaggre"
    ).build()
}
val mAgefansDao: AgefansDao by lazy { DB.agefansDao() }
val mQimanDao: QimanDao by lazy { DB.qimanDao() }

@Database(
    entities = [
        AgefansSearchKeywordHistory::class,
        QimanComicHistory::class,
        QimanComicBrowse::class,
        QimanComicDetail::class,
    ], version = 1
)
@TypeConverters(
    value = [
        ConverterDate::class,
        ConverterStringList::class,
        ConverterQimanComicChapterList::class,
        ConverterQimanComicHomeNormalList::class,
    ]
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun agefansDao(): AgefansDao
    abstract fun qimanDao(): QimanDao
}

class ConverterDate {
    @TypeConverter
    fun fromTimestamp(value: Long?): Date? {
        return value?.let { Date(it) }
    }

    @TypeConverter
    fun dateToTimestamp(date: Date?): Long? {
        return date?.time
    }
}

class ConverterStringList : ConverterList<String>()
class ConverterQimanComicChapterList : ConverterList<QimanComicChapter>()
class ConverterQimanComicHomeNormalList : ConverterList<QimanComicHomeNormal>()

open class ConverterList<T> {
    @TypeConverter
    fun fromList(value: MutableList<T>?): String? {
        if (value != null)
            return MoshiUtils.toJSONString(value)
        return null
    }

    @TypeConverter
    fun stringToList(date: String?): MutableList<T>? {
        if (date != null && date.startsWith("["))
            return JSON.parseArray(date, (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<T>)
        return null
    }
}
